<?php

namespace Common\Controller;

use Think\Controller;

class XuecheController extends Controller {

    /**
     *
     * 当前使用身份
     * 'user':后台
     * 'member':前台
     * @var string
     */
    protected $_identity = 'member';

    /**
     *
     * 用户信息
     * @var array 
     */
    protected $_memberInfo = array();

    /**
     *
     * 前台登录 ID
     * @var int
     */
    protected $_memberId = 0;

    /**
     *
     * 前台登录名称
     * @var string 
     */
    protected $_memberName = '';

    /**
     *
     * 后台登录ID
     * @var int
     */
    protected $_userId = 0;

    /**
     *
     * 令牌Key
     * @var string
     */
    const TOKEN_KEY = '%admin@3gvf32xibu@cloud!#%&&%gfje';

    /**
     *
     * 是否需要登录
     * @var bool
     */
    protected $_needLogin = false;

    /**
     *
     * 页面标题
     * 
     * @var string 
     */
    protected $_pageTitle = '永通学车';

    /**
     * 关键词
     * @var type 
     */
    protected $_pageKeywords = '永通学车,永通驾校';

    /**
     * 页面说明
     * @var type 
     */
    protected $_pageDescription = '永通学车,永通驾校';

    /**
     *
     * 登录后的用户/会员数据
     * @var array
     */
    protected $_info = array();

    /**
     * 当时时间
     * @var datetime
     */
    protected $_startTime = NULL;

    /**
     *
     * 当前页
     * @var int
     */
    protected $_page = 1;

    /**
     *
     * limit start
     * @var int
     */
    protected $_start = 0;

    /**
     *
     * order
     * @var string
     */
    protected $_order = '';

    /**
     *
     * @var type 
     */
    protected $_emptyData = '暂无相关数据';

    /**
     * 当前页
     * @var type 
     */
    protected $_currentActionPage = '';

    /**
     *
     * @var type 
     */
    protected $_url = '';
    private $_getfilter = "'|<[^>]*?>|^\\+\/v(8|9)|\\b(and|or)\\b.+?(>|<|=|\\bin\\b|\\blike\\b)|\\/\\*.+?\\*\\/|<\\s*script\\b|\\bEXEC\\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\\s+(TABLE|DATABASE)";
    private $_postfilter = "^\\+\/v(8|9)|\\b(and|or)\\b.{1,6}?(=|>|<|\\bin\\b|\\blike\\b)|\\/\\*.+?\\*\\/|<\\s*script\\b|<\\s*img\\b|\\bEXEC\\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\\s+(TABLE|DATABASE)";
    private $cookiefilter = "\\b(and|or)\\b.{1,6}?(=|>|<|\\bin\\b|\\blike\\b)|\\/\\*.+?\\*\\/|<\\s*script\\b|\\bEXEC\\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\\s+(TABLE|DATABASE)";

    /**
     *
     * 每页多少行，默认20
     * @var int
     */
    protected $_rows = 20;

    public function __construct() {
        parent::__construct();
        header('Content-type:text/html;charset=utf-8');
        import("Common.Library.Vendor.PhpCode.phpqrcode");
        import('Common.Library.ORG.Util.Input');
        import('Common.Library.ORG.Crypt.Base64');
        import('Common.Library.ORG.Util.Validate');
        $this->_info = session(C('USER_AUTH_KEY'));
        $this->_memberId = session('member_id');
        $this->_memberInfo = session('member');
    }

    public function _initialize() {
        if ($this->_needLogin) {
            switch ($this->_identity) {
                case 'member':
                    $this->MemberVerify();
                    break;
                case 'user':
                    import('Com.Xibu.Api.Logger');
                    $this->UserVerify();
                    break;
            }
            //dump($_SESSION);EXIT();
            $this->_startTime = getDateTime();
        }
    }

    /**
     * 初始化分页时需要的参数
     */
    protected function InitPage($rows = 0) {
        if ($this->_identity == 'user') {
            $page = $this->GetParam('pageNum');
        } else {
            $page = $this->GetParam('page');
        }
        $rows = $rows == 0 ? $this->_rows : $rows;

        //if($page<=0 || $page>21) $page = $this->page;
        if ($page <= 0) {
            $page = $this->_page;
        }
        if ($rows <= 0 || $rows > 500) {
            $rows = $this->_rows;
        }

        $this->_page = $page;  // 页码
        $this->_rows = $rows;
        $this->_start = ($page - 1) * $rows;
    }

    protected $numPerPage = 17;
    protected $pageNum;
    protected $offset;

    public function backPage($count) {
        $numPerPage = I('post.numPerPage');
        $this->numPerPage = empty($numPerPage) ? $this->numPerPage : $numPerPage;
        $pageNum = I('post.pageNum');
        $this->pageNum = empty($pageNum) ? 1 : $pageNum;
        $this->offset = ($this->pageNum - 1) * $this->numPerPage;

        $this->assign('totalCount', $count); //总条数 
        $this->assign('pageNum', $this->pageNum); //第几页
        $this->assign('numPerPage', $this->numPerPage); //每页显示多少条
        $this->assign('currentPage', $this->pageNum); //当前是第几页
    }

    /**
     *
     * 生成分页数据
     * @param $count
     */
    protected function ProcessPage($count, $conditions = array()) {
        import("ORG.Util.Page");
        $Page = new Page($count, $this->_rows);

        $Page->setConfig('prev', '<<'); //这个是更改“上一页”的样式
        $Page->setConfig('next', '>>'); //这个是更改“下一页”的样式
        $Page->setConfig('theme', '<link href="__PUBLIC__/Home/Cloud/Css/SquarePage.css" rel="stylesheet" type="text/css" />%upPage% %first% %prePage% %linkPage% %nextPage% %downPage% %end%');
        //分页跳转的时候保证查询条件
        if ($conditions) {
            foreach ($conditions as $key => $val) {
                $Page->parameter .= "$key=" . urlencode($val) . '&';
            }
        }

        if ($count == 0) {
            parent::assign('emptyData', $this->_emptyData);
        } else {
            parent::assign('emptyData', '');
        }

        if ($this->_identity == 'member') {
            $show = $Page->show();
            $this->assign('page', '<div class="page">' . $show . '</div>');
        } else if ($this->_identity == 'user') {

            $this->assign('totalCount', $count); // 总条数
            $this->assign('numPerPage', $this->_rows); // 每页显示多少条
            $this->assign('pageNumShown', 10); //页标数字多少个
            $this->assign('currentPage', $this->_page); //当前是第几页
        }
    }

    /**
     * 阻止攻击
     * @param type $inputValue
     * @param type $filterReg
     */
    private function _StopAttack($inputValue, $filterReg) {
        if (preg_match("/" . $filterReg . "/is", $inputValue) == 1) {
            echo '<script>document.location.href="' . $this->_url . '"</script>';
            exit();
        }
        return $inputValue;
    }

    /**
     *
     * 过滤输入数据
     *
     * @param mixed $param 参数名：a,b,c或array('a','b','c')
     *
     * @return string array $array array('a'=>1,'b'=>'2','c'=>3);
     */
    public function GetParam($param) {
        $arrVal = '';
        if (empty($param)) {
            return FALSE;
        }
        if (is_string($param)) {
            $param = explode(',', $param);
        }

        $single = FALSE;
        if (count($param) == 1) {
            $single = TRUE;
        }
        foreach ($param as $key) {
            $val = '';
            if ($key == 'recommend' || $key == 'content' || $key == 'html_code') {
                $val = $_REQUEST[$key];
            } else if ($key == 'message') {
                $val = $_POST[$key];
            } else if (isset($_POST[$key])) {
                $val = $this->_StopAttack($_POST[$key], $this->_postfilter);
            } else if (isset($_GET[$key])) {
                $val = $this->_StopAttack($_GET[$key], $this->_getfilter);
            }

            $arrVal[$key] = \Input::getInstance()->getVar($val);

            if ($single) {
                return $arrVal[$key];
            }
        }

        return $arrVal;
    }

    /**
     * 
     * 发站内信
     * @param mixed $member_id 
     * @param string $message 发送内容
     */
    protected function SendMsg($member_id, $message) {
        if (empty($member_id) && empty($message)) {
            return FALSE;
        }

        return Common::SysMsg($member_id, $message);
    }

    /**
     * 发送手机短信
     * 
     * @param string $number
     * @param string $message
     * @return boolean
     */
    protected function SendSMS($number, $message) {
        if (is_string($number)) {
            $number = explode(',', $number);
        }
        foreach ($number as $val) {
            $this->SMS($val, $message);
        }
    }

    /**
     * 发送手机短信
     * 
     * @param string $number
     * @param string $message
     * @return boolean
     */
    private function SMS($number, $message) {
        if (!\Validate::IsCellphone($number) && empty($message)) {
            return FALSE;
        }
        $url = 'http://120.25.202.19:8888/sms.aspx';
        //'http://106.ihuyi.cn/webservice/sms.php?method=Submit';
        $postData = 'action=send&extno=&userid=' . C('SMS_ID') . '&account=' . C('SMS_USER') . '&password=' . C('SMS_PASS');
        $postData .= '&mobile=' . $number . '&content=' . rawurlencode($message);
        //短信发送初始化
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_NOBODY, true);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
        $return_str = curl_exec($curl);
        curl_close($curl);
        //\Think\Log::write("send message:".var_export($return_str,1));
        preg_match("/<code>(\d+)<\/code>/", $return_str, $pre_arr_num);
        //\Think\Log::write("send message:".var_export($return_str))
        if ($pre_arr_num[1] == '2') {
            return true;
        } else {
            return false;
        } //0提交失败,2提交成功,408同一手机号码一分钟之内发送频率超过10条，系统将冻结你的帐号
    }

    /**
     * 邮件群发
     * 
     * @param mixed $mailto
     * @param string $subject
     * @param string $body
     * @return boolean
     */
    protected function SendMail($mailto, $subject, $body) {
        //return false;
        if (is_string($mailto)) {
            $mailto = explode(',', $mailto);
        }
        foreach ($mailto as $mail) {
            $this->MailTo($mail, $subject, $body);
        }
    }

    /**
     * 发送邮件
     * @param string $mailto
     * @param string $subject
     * @param string $body
     * @return boolean
     */
    private function MailTo($mailto, $subject, $body) {
        //Thinkphp的导入方式，放在/ThinkPHP/Extend/Vendor/
        //vendor('PHPMailer.class#phpmailer');
        import("Common.Library.Vendor.PHPMailer.class", '', '.phpmailer.php');
        //创建mail对象
        $mail = new PHPMailer();
        $mail->IsSMTP(); //设置使用SMTP服务器发送
        $mail->Host = "smtp.exmail.qq.com";  //设置发件箱的服务器 
        $mail->SMTPAuth = true;     // 设置需要验证
        $mail->Username = "regist@uli9.com";  // 发件人使用邮箱
        $mail->Password = 'ww.360.cn'; // 设置发件人密码
        $mail->From = "regist@uli9.com"; // 发件人邮箱
        $mail->FromName = C('SYS_NAME'); //发送者名称
        $mail->AddAddress($mailto); // 添加发送地址
        $mail->IsHTML(true); //指定支持html格式
        $mail->CharSet = "UTF-8";
        $mail->Subject = $subject;
        $mail->Body = $body;
        //dump($mail->Send());exit();
        if ($mail->Send()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     *
     * 后台登录判断
     */
    private function UserVerify() {
        //var_dump(session('user_id'));exit;
        $this->_userId = session('user_id');
        if (empty($this->_userId)) {
            $this->redirect('/admin/Login/index', null, 0, '');
            exit();
        }
        // $this->_userId = session('user_id');
        $this->_info = session(C('USER_AUTH_KEY'));
        $this->assign('userifon',  $this->_info);

//        if ($this->_info['username'] != 'admin') {
//            if (!in_array($nname, $nodelist["$mname"])) {
//                exit('<br /><br /><h1>抱歉,您没有操作权限!请联系: 549224868@qq.com</h1><br /><br /><h3><a href="' . C('ULI9') . '/HelloUli9/Index/logout">返回登录界面</a></h3>');
//            }
//        }
    }

    /**
     *
     * 前台会员登录判断
     */
    private function MemberVerify() {
        $logged_id = session('member_id');
        //var_dump($logged_id);exit;
        if ($logged_id > 0) {

            //$memberInfo = \Member::GetMemberInfo($this->_memberId);
            $memberInfo = D('Common/Members')->GetDataById($logged_id, 'member_id,nickname,name,sex,avatar,mobile');
            //this->_memberId = $memberInfo['member_id'];
            //var_dump($memberInfo);exit;
            session('member', $memberInfo);
            session('member_id', $memberInfo['member_id']);
            $this->_memberInfo = $memberInfo;
            $this->_memberId = $memberInfo['member_id'];
            //var_dump($memberInfo);exit;
        }
        //var_dump($this->_memberId);exit;
        if ($this->_needLogin) {
            if (empty($this->_memberId)) {
                //exit('baidu');
                header("location:" . __MODULE__ . '/Index/index');
                exit();
            }
        }
    }

    /**
     *
     * 游客登录判断,用于游客
     */
    private function GuestVerify() {
        
    }

    /**
     *
     * 令牌检测
     */
    protected function CheckToken() {
        $params = $this->GetParam('t,tk');
        if (abs($params['t'] - time()) > 10) {
            $this->error('操作超时', '/');
        }
        if (md5($params['t'] . XibuAction::TOKEN_KEY) != $params['tk']) {
            $this->error('非法操作', '/');
        }
    }

    /**
     * 输出Json
     */
    protected function ParseJson($result) {
        exit(json_encode($result));
    }

    /**
     * 直接跳转,url为空直接返回上一页
     * @param type $url
     */
    public function GoToURL($url = '') {
        if (empty($url)) {
            $url = $_SERVER["HTTP_REFERER"];
        }

        header("location:" . $url);
        exit();
    }

    /**
     * 404页面
     */
    public function NoPage() {
        header('location:' . '/');
        exit();
    }

    /**
     * 必需登录
     */
    public function RequiredLogin() {
        $this->_needLogin = TRUE;
        $this->MemberVerify();
    }

    /**
     * 
     * @param type $message
     * @param type $jumpUrl
     * @param type $ajax
     */
    public function successJS($message, $jumpUrl = '', $ajax = false) {
        //parent::success($message, $jumpUrl, $ajax);
        $jsAlert = '<script  type="text/javascript">alert("' . $message . '");document.location.href="' . $jumpUrl . '"</script>';
        exit($jsAlert);
    }

    /**
     * 
     * @param type $message
     * @param type $jumpUrl
     * @param type $ajax
     */
    public function errorJS($message, $jumpUrl = '', $ajax = false) {
        $jsAlert = '<script  type="text/javascript">alert("' . $message . '");document.location.href="' . $jumpUrl . '"</script>';
        exit($jsAlert);
    }

    /**
     * aaaign公用
     */
    public function AssignPublic() {


        parent::assign('pageTitle', $this->_pageTitle);      //页面标题
        parent::assign('pageKeywords', $this->_pageKeywords);      //页面标题
        parent::assign('pageDescription', $this->_pageDescription);      //页面描述
        //搜索关键字
        parent::assign('keyword', $this->GetParam('keyword'));

        parent::assign('siteUrl', C('SYS_SITE'));

        if ($this->_identity == 'member') {
            $memberInfo = $this->_memberInfo;
            //$avatar = getAvatar($this->_memberId, $memberInfo['avatar']);
            //parent::assign('avatar', $avatar);
            parent::assign('loggedID', $this->_memberId);       //已登录ID
            parent::assign('loggedName', $this->_memberName);   //登录名称
        }
        //parent::assign('actionName', $this->getActionName());    //当前ActionName
        parent::assign('currentActionPage', $this->_currentActionPage);
    }

    /**
     * 
     * @param type $templateFile
     * @param type $charset
     * @param type $contentType
     */
    public function display($templateFile = '', $charset = '', $contentType = '', $content = '', $prefix = '') {
        parent::display($templateFile, $charset, $contentType, $content, $prefix);
        $this->AssignPublic();
    }

    /**
     * ajax 登录验证提醒
     */
    protected function AjaxLogin() {
        if ($this->_memberId <= 0) {
            echo '请先登录！';
            exit();
        }
    }

    /**
     * 图片上传处理
     * @return type
     */

    public function UploadImg(array $config){
        $configs = array(
            'rootPath'      =>  I('server.DOCUMENT_ROOT').'/Public/Uploads', //保存根路径
            'maxSize' => empty($config['maxSize'])?0:$config['maxSize'], 
            'savePath' => empty($config['savePath'])?'/default':$config['savePath'],  
            //'saveName' => empty($config['saveName'])?'':$config['saveName'], 
            'exts' => empty($config['exts'])?array('jpg', 'gif', 'png', 'jpeg'):$config['exts'], 
            'autoSub' => empty($config['autoSub'])?false:$config['autoSub'], //开启子目录保存 
            'subName' => empty($config['subName'])?'getSubName':$config['subName'],
            );
        $upload = new \Think\Upload($configs); // 实例化上传类  
        $info = $upload->upload();
        // 采用时间戳命名
        $upload->saveName = 'time';
        if (!$info) {// 上传错误提示错误信息        
            \Think\Log::write('sssssss ttttt Error :' . var_export($_FILES, 1));
            \Think\Log::write('Upload Files Error :' . var_export($upload->getError(), 1));
            return array('status' => 'error', 'msg' => $upload->getError());
        }else {// 上传成功  
            $targetFile = '/Public/Uploads'.$info['image']['savepath'].$info['image']['savename'];
            $image_id = md5(time().getRandStr());
            $imgs = array(
                'image_id' => $image_id,
                'storage' => 'file',
                'url' => $targetFile,
                'last_modified' => time()
            );
            D('Common/Image')->SaveData($imgs);
            return array('status' => 200, 'msg' => $targetFile,'image_id'=>$image_id);
        }
    }

}
